package com.jws.jawestshow;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.zkteco.android.IDReader.IDPhotoHelper;
import com.zkteco.android.IDReader.WLTService;
import com.zkteco.android.biometric.core.device.ParameterHelper;
import com.zkteco.android.biometric.core.device.TransportType;
import com.zkteco.android.biometric.core.utils.LogHelper;
import com.zkteco.android.biometric.module.idcard.IDCardReader;
import com.zkteco.android.biometric.module.idcard.IDCardReaderFactory;
import com.zkteco.android.biometric.module.idcard.exception.IDCardReaderException;
import com.zkteco.android.biometric.module.idcard.meta.IDCardInfo;
import com.zkteco.android.biometric.module.idcard.meta.IDPRPCardInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;


public class IDCardReaderActivity extends Activity {
    private static final int VID = 1024;    //IDR VID
    private static final int PID = 50010;     //IDR PID
    private IDCardReader idCardReader = null;
    private TextView textView = null;
    private ImageView imageView = null;
    private boolean bopen = false;
    private boolean bStoped = false;
    private int mReadCount = 0;
    private CountDownLatch countdownLatch = null;

    private Context mContext = null;
    private UsbManager musbManager = null;
    private final String ACTION_USB_PERMISSION = "com.jws.jawestshow.USB_PERMISSION";

    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
//                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true)) {
                        OpenDevice();
                    } else {
                        Toast.makeText(mContext, getString(R.string.jws_usb_unauthorized), Toast.LENGTH_SHORT).show();
                        //mTxtReport.setText("USB未授权");
                    }
                }
            }
        }
    };

    private void RequestDevicePermission() {
        musbManager = (UsbManager) this.getSystemService(Context.USB_SERVICE);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        mContext.registerReceiver(mUsbReceiver, filter);

        for (UsbDevice device : musbManager.getDeviceList().values()) {
            if (device.getVendorId() == VID && device.getProductId() == PID) {
                Intent intent = new Intent(ACTION_USB_PERMISSION);
                PendingIntent pendingIntent = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
                    pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_IMMUTABLE);
                } else {
                    pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);
                }
                musbManager.requestPermission(device, pendingIntent);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.idcard_main);
        textView = (TextView) findViewById(R.id.textView);
        imageView = (ImageView) findViewById(R.id.imageView);
        mContext = this.getApplicationContext();

    }

    public Context getContext() {
        return this.getApplicationContext();
    }

    private void startIDCardReader() {
        // Define output log level
        LogHelper.setLevel(Log.VERBOSE);
        // Start fingerprint sensor
        Map idrparams = new HashMap();
        idrparams.put(ParameterHelper.PARAM_KEY_VID, VID);
        idrparams.put(ParameterHelper.PARAM_KEY_PID, PID);
        idCardReader = IDCardReaderFactory.createIDCardReader(this, TransportType.USB, idrparams);
        idCardReader.setLibusbFlag(true);
    }

    private void stopIDCardReader() {
        if (!bopen) {
            return;
        }
        bStoped = true;
        mReadCount = 0;
        if (null != countdownLatch) {
            try {
                countdownLatch.await(2, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            idCardReader.close(0);
        } catch (IDCardReaderException e) {
            e.printStackTrace();
        }

        bopen = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopIDCardReader();
        // Destroy fingerprint sensor when it's not used
        IDCardReaderFactory.destroy(idCardReader);
    }

    public static void writeLogToFile(String log) {
        String LogPath = Environment.getExternalStorageDirectory() + File.separator + "zkteco";
        try {
            File dirFile = new File(LogPath);  //目录转化成文件夹
            if (!dirFile.exists()) {              //如果不存在，那就建立这个文件夹
                dirFile.mkdirs();
            }
            String path = LogPath + File.separator +"idrlog.txt";
            File file = new File(path);
            if (!file.exists()) {
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
            FileOutputStream outStream = new FileOutputStream(file, true);
            log += "\r\n";
            outStream.write(log.getBytes());
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean authenticate() {
        try {
            idCardReader.findCard(0);
            idCardReader.selectCard(0);
            return true;
        } catch (IDCardReaderException e) {
            return false;
        }
    }

    public void OpenDevice() {
        if (bopen) {
            textView.setText(getString(R.string.jws_device_connected));
            return;
        }
        try {
            startIDCardReader();
            idCardReader.open(0);
            bStoped = false;
            mReadCount = 0;
            writeLogToFile("Connect to device succeeded");
            textView.setText(getString(R.string.jws_device_connection_succeeded));
            bopen = true;
            countdownLatch = new CountDownLatch(1);
            new Thread(new Runnable() {
                public void run() {
                    while (!bStoped) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        boolean ret = false;
                        final long nTickstart = System.currentTimeMillis();
                        try {
                            idCardReader.findCard(0);
                            idCardReader.selectCard(0);
                        } catch (IDCardReaderException e) {
                            //continue;
                        }
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        int retType = 0;
                        try {
                            retType = idCardReader.readCardEx(0, 0);
                        } catch (IDCardReaderException e) {
                            writeLogToFile("Read card failed, Exception: " + e.getMessage());
                        }
                        if (retType == 1 || retType == 2 || retType == 3) {
                            final long nTickUsed = (System.currentTimeMillis() - nTickstart);
                            final int final_retType = retType;
                            writeLogToFile("Read card successfully：" + (++mReadCount) + " times" + "，use time：" + nTickUsed + "ms");
                            runOnUiThread(new Runnable() {
                                @SuppressLint("SetTextI18n")
                                public void run() {
                                    if(bopen) {
                                        if (final_retType == 1) {
                                            final IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
                                            //姓名adb
                                            String strName = idCardInfo.getName();
                                            //性别
                                            String strSex = idCardInfo.getSex();
                                            //民族
                                            String strNation = idCardInfo.getNation();
                                            //出生日期
                                            String strBorn = idCardInfo.getBirth();
                                            //住址
                                            String strAddr = idCardInfo.getAddress();
                                            //身份证号
                                            String strID = idCardInfo.getId();
                                            //有效期限
                                            String strEffext = idCardInfo.getValidityTime();
                                            //签发机关
                                            String strIssueAt = idCardInfo.getDepart();
                                            textView.setText(getString(R.string.jws_read_times) + mReadCount + ", "
                                                    + getString(R.string.jws_use_time) + nTickUsed + getString(R.string.jws_ms) + "\n"
                                                    + getString(R.string.jws_resident_id_card) + "\n"
                                                    + getString(R.string.jws_name) + strName + "\n"
                                                    + getString(R.string.jws_sex) + strSex + "\n"
                                                    + getString(R.string.jws_nation) + strNation + "\n"
                                                    + getString(R.string.jws_birth) + strBorn + "\n"
                                                    + getString(R.string.jws_address) + strAddr + "\n"
                                                    + getString(R.string.jws_card_number) + strID + "\n"
                                                    + getString(R.string.jws_issuing_authority) + strIssueAt + "\n"
                                                    + getString(R.string.jws_validity) + strEffext);
                                            if (idCardInfo.getPhotolength() > 0) {
                                                byte[] buf = new byte[WLTService.imgLength];
                                                if (1 == WLTService.wlt2Bmp(idCardInfo.getPhoto(), buf)) {
                                                    imageView.setImageBitmap(IDPhotoHelper.Bgr2Bitmap(buf));
                                                }
                                            }
                                        } else if (final_retType == 2) {
                                            final IDPRPCardInfo idprpCardInfo = idCardReader.getLastPRPIDCardInfo();
                                            //中文名
                                            String strCnName = idprpCardInfo.getCnName();
                                            //英文名
                                            String strEnName = idprpCardInfo.getEnName();
                                            //国家/国家地区代码
                                            String strCountry = idprpCardInfo.getCountry() + "/" + idprpCardInfo.getCountryCode();//国家/国家地区代码
                                            //出生日期
                                            String strBorn = idprpCardInfo.getBirth();
                                            //身份证号
                                            String strID = idprpCardInfo.getId();
                                            //有效期限
                                            String strEffext = idprpCardInfo.getValidityTime();
                                            //签发机关
//                                        String strIssueAt = "公安部";

                                            textView.setText(getString(R.string.jws_read_times) + mReadCount + ", "
                                                    + getString(R.string.jws_use_time) + nTickUsed + getString(R.string.jws_ms) + "\n"
                                                    + getString(R.string.jws_foreigner_permanent_residence_permit) + "\n"
                                                    + getString(R.string.jws_chinese_name) + strCnName + "\n"
                                                    + getString(R.string.jws_english_name) + strEnName + "\n"
                                                    + getString(R.string.jws_country) + strCountry + "\n"
                                                    + getString(R.string.jws_certificate_number) + strID + "\n");

                                            if (idprpCardInfo.getPhotolength() > 0) {
                                                byte[] buf = new byte[WLTService.imgLength];
                                                if (1 == WLTService.wlt2Bmp(idprpCardInfo.getPhoto(), buf)) {
                                                    imageView.setImageBitmap(IDPhotoHelper.Bgr2Bitmap(buf));
                                                }
                                            }
                                        } else {
                                            final IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
                                            //姓名
                                            String strName = idCardInfo.getName();
                                            //民族,港澳台不支持该项
                                            String strNation = "";
                                            //出生日期
                                            String strBorn = idCardInfo.getBirth();
                                            //住址
                                            String strAddr = idCardInfo.getAddress();
                                            //身份证号
                                            String strID = idCardInfo.getId();
                                            //有效期限
                                            String strEffext = idCardInfo.getValidityTime();
                                            //签发机关
                                            String strIssueAt = idCardInfo.getDepart();
                                            //通行证号
                                            String strPassNum = idCardInfo.getPassNum();
                                            //签证次数
                                            int visaTimes = idCardInfo.getVisaTimes();

                                            textView.setText(getString(R.string.jws_read_times) + mReadCount + ", "
                                                    + getString(R.string.jws_use_time) + nTickUsed + getString(R.string.jws_ms) + "\n"
                                                    + getString(R.string.jws_hk_macao_tw_residence_permit) + "\n"
                                                    + getString(R.string.jws_name) + strName + "\n"
                                                    + getString(R.string.jws_address) + strAddr + "\n"
                                                    + getString(R.string.jws_card_number) + strID + "\n"
                                                    + getString(R.string.jws_pass_number) + strPassNum + "\n"
                                                    + getString(R.string.jws_number_of_visas) + visaTimes);

                                            if (idCardInfo.getPhotolength() > 0) {
                                                byte[] buf = new byte[WLTService.imgLength];
                                                if (1 == WLTService.wlt2Bmp(idCardInfo.getPhoto(), buf)) {
                                                    imageView.setImageBitmap(IDPhotoHelper.Bgr2Bitmap(buf));
                                                }
                                            }
                                        }
                                    }
                                }
                            });
                        }
                    }
                    countdownLatch.countDown();
                }
            }).start();
        } catch (IDCardReaderException e) {
            writeLogToFile("Connect to device failed");
            textView.setText(getString(R.string.jws_read_card_failed));
            textView.setText(getString(R.string.jws_read_card_failed_error_code) + e.getErrorCode() + "\n"
                    + getString(R.string.jws_error_message) + "：" + e.getMessage() + "\n"
                    + getString(R.string.jws_error_code) + "=" + e.getInternalErrorCode());
        }

    }

    public void OnBnBegin(View view) throws IDCardReaderException {

        if (bopen) {
            textView.setText(getString(R.string.jws_device_connected));
            return;
        }
        RequestDevicePermission();

    }

    public void OnBnStop(View view) {
        stopIDCardReader();
        textView.setText(getString(R.string.jws_device_disconnected));
    }

}

